﻿using System.Text.RegularExpressions;
using WF_AppFuel.Base.Exceptions;
using WF_AppFuel.Validation.Base;

namespace WF_AppFuel.Validation.Engines
{
    /// <summary>
    /// This engine is used for validating Email fields.
    /// </summary>
    /// <author>Dennis Q. Pitallano</author>
    public sealed class IsEmailValidationEngine : BaseValidationEngine
    {
        //Constant pattern to be used by the Regex class.
        private const string EMAIL_ADDRESS_PATTERN = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
            + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
            + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
            + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        //Pre-compile Regex instance using the pattern.
        private static Regex emailRegex = new Regex(EMAIL_ADDRESS_PATTERN);

        public override bool Run()
        {
            if (Value == null)
                return false;

            if (Value is string)
                if (string.IsNullOrEmpty(Value.ToString().Trim()))
                    return false;

            return emailRegex.IsMatch(Value.ToString());
        }
    }
}
